#!/bin/bash

# Detect the device that's used for the root file system
DEVICEBASE=`mount | grep " / " | awk '{print $1}' | sed s/[0-9]\$//`
DEVICE=`echo $DEVICEBASE | sed s/p\$//`

if [ -f /resize-me.2 ]; then
 echo "Resizing file system on ${DEVICEBASE}2"
 resize2fs -p ${DEVICEBASE}2
 rm /resize-me.2
fi

if [ ! -f /resize-me ]; then
 echo "/resize-me does not exist, aborting"
 exit
fi

# Delete Partitions
for N in 2 3 4; do 
if [ -b ${DEVICEBASE}$N ]; then
fdisk $DEVICE <<EOT
d
$N
w
EOT
partprobe
echo p | fdisk $DEVICE
fi
done

# Find the last sector of partition 1
P0=`echo "p"  | fdisk /dev/mmcblk0  | grep "p1 " | awk '{print $4}'`

# Size of partition 2 and 3 depends on SD card size
# on a 16GB+ card, we'll use two 4GB system partitions
SIZE=$(lsblk -bno SIZE /dev/mmcblk0 | head -1)
P1=$((P0+1))
P2=$((P0+3000000))
P3=$((P0+3000001))
P4=$((P0+6000000))
if [ $SIZE -gt 15000000000 ]; then
  P1=$((P0+1))
  P2=$((P0+8000000))
  P3=$((P0+8000001))
  P4=$((P0+16000000))
fi
if [ $SIZE -gt 30000000000 ]; then
  P1=$((P0+1))
  P2=$((P0+16000000))
  P3=$((P0+16000001))
  P4=$((P0+32000000))
fi

echo "New partitions:"
echo "p2: $P1 .. $P2"
echo "p2: $P3 .. $P4"
sleep 4

# Create partitions 2 and 3
fdisk $DEVICE <<EOT
n
p
2
$P1
$P2
n
p
3
$P3
$P4
w
EOT
partprobe
echo p | fdisk $DEVICE

sleep 10

# Create partition 4
fdisk $DEVICE <<EOT
n
p


w
EOT
partprobe
echo p | fdisk $DEVICE

e2fsck -f -p ${DEVICEBASE}2

rm /resize-me
touch /resize-me.2

# Create fs in partition 4 if there is none
fsck.f2fs -p -f ${DEVICEBASE}4
RET=$?
if [[ $RET == 8 || $RET==255 ]] ; then
  mkfs -t f2fs -f ${DEVICEBASE}4
fi

echo "Resized partitions" >> /tmp/reboot
